/****同步课程***/
//记录本地已有的课程id
var currCourseids;
var addedcourseids='';//已经添加的课程
//记录所有课程数据，以便存储到本地
var courseList;
var courseCount = 1;
var keyword='';
//公共类
var localStorageManagers = require("script/localStorageManagers.js");
var downloadUtils = require('scripts/Core/DownLoadUtil.js');
var mobileFrame = require('scripts/Core/MobileFrame.js');
//mui初始化
mui.init({
	swipeBack: true //启用右滑关闭功能
});
mui('.mui-scroll-wrapper').scroll({
					indicators: false //是否显示滚动条
				});
//加载plusReady
if (window.plus) {
	plusReady();
} else {
	document.addEventListener("plusready", plusReady, false);
}
//
function enterSearch(e) {
    if(e.keyCode == 13) {
        keyword=document.getElementById('searchinput').value;
		loadCourse();
    }
}
//
function plusReady() {
	currCourseids = '';
	courseList = new Array();
	addedcourseids=plus.webview.currentWebview().currCourseids;//已经添加的课程
	loadCourse();
	//查看课程
	mui('#coursesdiv').on('tap', '.course-top', showResView);
	//打开添加课程
	mui('header').on('tap', '#addselfcourse', openAddSelfcourse);
	//保存选择课程
	mui('header').on('tap', '#saveselfcourse', saveSelfcourse);
	//搜索
	mui('.mui-content').on('focusout','#searchinput',function(){
		keyword=document.getElementById('searchinput').value;
		loadCourse();
	});
};
//加载课程
function loadCourse(courseid) {
	document.getElementById('coursesdiv').innerHTML = ' ';
	addedcourseids+=','+courseid
	//loadCourseLocal(); //加载本地课程
	if (hasNet()) loadCourseAjax(); //ajax加载课程
}
//是否有网
function hasNet() {
	var isNet = mobileFrame.IsNetWorkCanUse();
	return isNet;
}
//本地加载
function loadCourseLocal() {
	courseList = localStorageManagers.getSynccourseSession();
	if (courseList != null) {
		var courseulEle = document.getElementById("courseul");
		mui.each(courseList, function(index, course) {
			currCourseids += course.courseId + ",";
			buildCourseDiv(course);
			courseCount++;
		});
	}
}
//远程加载课程列表数据
function loadCourseAjax() {
	if (courseList == null) courseList = new Array();
	if (currCourseids.length > 0) currCourseids = currCourseids.substring(0, currCourseids.length - 1);
	//var userid = localStorage.getItem("userid");
	var userid = localStorageManagers.getUseridSession();
	console.log(serverAjax + 'mobile/course/getStudentSchoolBuyCourseList.do');
	mui.ajax(serverAjax + 'mobile/course/getStudentSchoolBuyCourseList.do', {
		data: {
			userid: userid,
			currCourseids: currCourseids
		},
		dataType: 'json', //服务器返回json格式数据
		type: 'post', //HTTP请求类型
		timeout: 10000, //超时时间设置为10秒；
		success: function(data) {
			if (data.length == 0) {
				ifHasnewCourse = false;
				return;
			}
			for (var i = 0; i < data.length; i++) {
				var course = data[i];
				courseList.push(course);
				buildCourseDiv(course);
				courseCount++;
			}
			localStorageManagers.setSynccourseSession(courseList);
		},
		error: function(xhr, type, errorThrown) {
			ajaxErrorTip();
			//异常处理；
			console.log(xhr);
		}
	});
}
//打开课程资源页面
function showResView() {
	var type=2;
	var courseid = this.parentNode.getAttribute('courseid');
	if(addedcourseids.indexOf(courseid)>=0)type=1;
	mui.openWindow({
		url: 'selfcoursecatalog.html',
		id: 'selfcenter/selfstudycourse/selfcoursecatalog',
		extras: {
			'courseid': courseid,
			'type':type
		}
	});
}

function getBackColor() {
	var bColor = 'b1';
	var yu = courseCount % 4;
	switch (yu) {
		case 1:
			bColor = 'b1';
			break;
		case 2:
			bColor = 'b2';
			break;
		case 3:
			bColor = 'b3';
			break;
		case 0:
			bColor = 'b4';
			break;
	}
	return bColor;
}
//构建课程div
function buildCourseDiv(course) {
	if(course.title.indexOf(keyword)<0)return;
	
	var addedstr='';
	var checkvalue=course.courseId;
	if(course.status==100){
		addedstr=' checked disabled="disabled"';
		checkvalue='';
	}
	var courseDivEle = document.getElementById('courseid_' + course.courseId);
	if (courseDivEle != null) courseDivEle.parentNode.removeChild(courseDivEle);
	var bColor = getBackColor();
	var viewcount=0;
	if(course.viewCount>0)viewcount=course.viewCount;
	var imgpath='../../images/coursedefault.png';
	if(course.imagePath.length>0)imgpath=fileServerAjax+course.imagePath;
	var divstr = '<div class="mui-course" id="courseid_' + course.courseId + '" courseid="' + course.courseId + '">' + '<div class="course-top ' + bColor + '"><div class="courseimg"><img src="'+imgpath+'" ></div>' +
		'<div class="c1">' + '<span class="cmsg"><img src="../../images/tip.png" />&nbsp;教师上传了计机械设计机械设计机</span> ' + '<span class="cname">' + course.title + '</span>  ' + '<span class="ctype">'+course.catName+'</span>' + ' </div>' + '<div class="c2">' + '<span class="cuser"><img src="../../images/tou.png" />&nbsp;'+viewcount+'学生学习</span>' + '</div>' + '</div>' +
		' <div class="checkboxdiv"><div class="mui-input-row mui-checkbox"><label></label><input name="checkbox1" value="' + checkvalue + '" type="checkbox" '+addedstr+'></div></div>' + '</div>';

	document.getElementById('coursesdiv').innerHTML = document.getElementById('coursesdiv').innerHTML + divstr;
}
//下载资源
function downloadResource(src) {
	// plus.downloader.enumerate(function(tasks){
	//  	alert("当前下载任务数量:"+tasks.length);
	//  });
	//调用父页面方法

	downloadUtils.downloadFileWidthLocalCache(src, {
		beforeDownload: function() {
			//记录该下载资源信息：资源本身信息，课程、课题信息
		},
		successDownload: function(relativePath) {
			console.log('下载成功:' + relativePath);
			mui.plusReady(function() {
				var sd_path = plus.io.convertLocalFileSystemURL(relativePath);
				console.log('存储路径：' + sd_path);
			});
		},
		errorDownload: function(msg) {}
	});
	//var curTasks=DownloadUtil.getCurrentDownloadTasks();
	//var conCurTasks=DownloadUtil.getConcurrentDownloadTask();
	// mui.toast("当前下载任务数量:"+conCurTasks.CurrentTaskCount);
};
//打开添加课程页面
function openAddSelfcourse() {
	mui.openWindow({
		url: 'addselfstudy.html',
		id: 'selfcenter/selfstudycourse/addselfstudy'
	});
}
//保存选择的课程
function saveSelfcourse() {
	var courseids = '';
	var inputcs = document.getElementsByTagName('input');
	for (var i = 0; i < inputcs.length; i++) {
		var inputc = inputcs[i];
		if(inputc.value.length==0)continue;
		if (inputc.checked) courseids += inputc.value+',';
	}
	if(courseids.length>0)courseids=courseids.substring(0,courseids.length-1);
	if(courseids.length<=0){
		mui.toast("请选择需要添加的课程");
		return;
	}
	var userid = localStorageManagers.getUseridSession();
	var url=serverAjax+"mobile/course/addSelfCourse.do"
	mui.ajax(url,{
		data:{'userid':userid,'courseids':courseids},
		dataType:'json',
		type:'post',
		timeout:10000,
		success:function(data){
			mui.toast('添加成功');
			var parentWebView = plus.webview.getWebviewById("selfcenter/selfstudycourse/studycourseindex");
	        parentWebView.evalJS("loadCourse()");
	 		mui.back();
		},
		error: function(xhr, type, errorThrown) {
			ajaxErrorTip();
			//异常处理；
			console.log(xhr);
		}
	});
}